package com.by.datasource.dynamictablename.algorithm;

import cn.hutool.extra.spring.SpringUtil;
import com.by.datasource.dynamictablename.algorithm.annotation.DyTNAlgorithm;
import com.by.toolkitspring.customizeannotation.AbstractByAnnotationContext;
import com.by.toolkitspring.customizeannotation.ByAnnotationProcessor;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.Map;

@Slf4j
public class DyTNAlgorithmContext implements AbstractByAnnotationContext<DyTNAlgorithm> {

    private static final Map<Integer, Class<?>> TABLE_DYNAMIC_TABLE_NAME_MAP = Maps.newHashMap();

    @Override
    public void receiveContext(List<ByAnnotationProcessor.CustomizeAnnotationInfo> infos) {
        if (CollectionUtils.isEmpty(infos)) {
            return;
        }
        infos.forEach(info -> {
            DyTNAlgorithm dyTNAlgorithm = info.getBeanClass().getAnnotation(DyTNAlgorithm.class);
            int value = dyTNAlgorithm.value();
            TABLE_DYNAMIC_TABLE_NAME_MAP.put(value, info.getBeanClass());
        });
    }

    public AbstractDyTNAlgorithm algorithmInstance(Integer algorithm) {
        return (AbstractDyTNAlgorithm) SpringUtil.getBean(TABLE_DYNAMIC_TABLE_NAME_MAP.get(algorithm));
    }

}
